package com.example.sqlite.activities;

import java.util.List;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.example.sqlite.dao.ContactsDAO;
import com.example.sqlite.models.Contact;

public class MainActivity extends ListActivity {

	private ContactsDAO dao;

	@Override
	protected void onCreate( Bundle savedInstanceState ) {
		super.onCreate( savedInstanceState );
		setContentView( R.layout.activity_main );

		dao = new ContactsDAO( this );
		dao.open();

	}

	@Override
	protected void onResume() {
		dao.open();
		super.onResume();
		List<Contact> contacts = dao.getAll();

		ArrayAdapter<Contact> adapter = new ArrayAdapter<Contact>( this, android.R.layout.simple_list_item_1, contacts );
		setListAdapter( adapter );
	}

	@Override
	protected void onPause() {
		dao.close();
		super.onPause();
	}

	@Override
	public boolean onCreateOptionsMenu( Menu menu ) {
		getMenuInflater().inflate( R.menu.activity_main, menu );
		return true;
	}

	@Override
	public boolean onOptionsItemSelected( MenuItem item ) {
		if ( item.getItemId() == R.id.add_contact ) {
			Intent intent = new Intent( MainActivity.this, AddContactActivity.class );
			startActivity( intent );
		}
		return super.onOptionsItemSelected( item );
	}

	@Override
	protected void onListItemClick( ListView l, View v, int position, long id ) {
		ListAdapter adapter = getListAdapter();
		Contact obj = (Contact) adapter.getItem( position );
		Intent intent = new Intent( MainActivity.this, ShowContactActivity.class );
		intent.putExtra( "id", obj.getId() );
		startActivity( intent );
		// teste
		super.onListItemClick( l, v, position, id );
	}

}
